<?php

namespace Backend;

use Lib\Acl;
use Phalcon\Loader;
use Phalcon\Mvc\View;
use Phalcon\Mvc\View\Engine\Volt;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\Mvc\ModuleDefinitionInterface;


class Module implements ModuleDefinitionInterface
{

    public function registerAutoloaders()
    {
        $loader = new Loader();
        $loader->registerNamespaces(array(
            'Backend\Controllers' => __DIR__ . '/controllers/',
            'Models' => __DIR__ . '/../models/',
        ));
        $loader->register();
    }

    public function registerServices($di)
    {
        $config = include __DIR__ . "/../config/config.php";
        $di['view'] = function () use ($config) {
            $view = new View();
            $view->setViewsDir(__DIR__ . '/views/');
            $view->registerEngines(array(
                '.phtml' => function ($view, $di) use ($config) {
                        $volt = new Volt($view, $di);
                        $volt->setOptions(array(
                            'compiledPath' => $config->template->cacheDir,
                            'compileAlways' => $config->template->compileAlways
                        ));
                        return $volt;
                    }
            ));
            return $view;
        };
        $di['db'] = function () use ($config) {
            return new DbAdapter(array(
                "host" => $config->database->host,
                "username" => $config->database->username,
                "password" => $config->database->password,
                "dbname" => $config->database->dbname,
                "charset" => $config->database->charset,
            ));
        };
        $dispatcher = $di['dispatcher'];
        $eventManager = new \Phalcon\Events\Manager();
        $eventManager->attach('dispatch', new Acl());
        $dispatcher->setEventsManager($eventManager);
    }
}
